import { defineStore } from 'pinia'
import api from '@/utils/api'

export const useSectionsStore = defineStore('sections', {
  state: () => ({
    sections: [],
    pagination: null,
    currentSection: null,
    currentProjectId: null
  }),

  getters: {
    getSections: (state) => state.sections,
    getPagination: (state) => state.pagination,
    getCurrentSection: (state) => state.currentSection,
    // 获取当前章节的所有表单
    getCurrentSectionForms: (state) => state.currentSection?.forms || []
  },

  actions: {
    // 设置当前项目ID
    setCurrentProjectId(projectId) {
      this.currentProjectId = projectId
    },

    // 获取项目章节列表
    async fetchSections(projectId = null, params = {}) {
      try {
        const id = projectId || this.currentProjectId
        if (!id) {
          throw new Error('项目ID不能为空')
        }
        
        const response = await api.sections.list(id, params)
        this.sections = response.data || []
        this.pagination = response.pagination || null
        return {
          data: this.sections,
          pagination: this.pagination
        }
      } catch (error) {
        console.error('获取章节列表失败:', error)
        throw error
      }
    },

    // 获取章节详情
    async fetchSectionById(sectionId) {
      try {
        const response = await api.sections.getById(sectionId)
        return response.data
      } catch (error) {
        console.error('获取章节详情失败:', error)
        throw error
      }
    },

    // 创建章节
    async createSection(sectionData, projectId = null) {
      try {
        const id = projectId || this.currentProjectId
        if (!id) {
          throw new Error('项目ID不能为空')
        }
        
        const response = await api.sections.create(id, sectionData)
        const newSection = response.data
        
        // 更新本地状态
        this.sections.push(newSection)
        return newSection
      } catch (error) {
        console.error('创建章节失败:', error)
        throw error
      }
    },

    // 更新章节
    async updateSection(sectionData) {
      try {
        const response = await api.sections.update(sectionData.id || sectionData._id, sectionData)
        const updatedSection = response.data
        
        // 更新本地状态
        const index = this.sections.findIndex(s => s._id === updatedSection._id || s.id === updatedSection._id)
        if (index !== -1) {
          this.sections[index] = updatedSection
        }
        
        return updatedSection
      } catch (error) {
        console.error('更新章节失败:', error)
        throw error
      }
    },

    // 删除章节
    async deleteSection(sectionId) {
      try {
        await api.sections.delete(sectionId)
        
        // 更新本地状态
        const index = this.sections.findIndex(s => s._id === sectionId || s.id === sectionId)
        if (index !== -1) {
          this.sections.splice(index, 1)
        }
        
        if (this.currentSection?._id === sectionId || this.currentSection?.id === sectionId) {
          this.currentSection = null
        }
        
        return true
      } catch (error) {
        console.error('删除章节失败:', error)
        throw error
      }
    },

    // 重新排序章节
    async reorderSections(sectionsOrder, projectId = null) {
      try {
        const id = projectId || this.currentProjectId
        if (!id) {
          throw new Error('项目ID不能为空')
        }
        
        const response = await api.sections.reorder(id, sectionsOrder)
        this.sections = response.data || []
        return this.sections
      } catch (error) {
        console.error('重新排序章节失败:', error)
        throw error
      }
    },

    // 设置当前章节
    setCurrentSection(section) {
      this.currentSection = section
    },

    // 添加表单到章节
    async addFormToSection(sectionId, form) {
      try {
        const section = this.sections.find(s => s._id === sectionId || s.id === sectionId)
        if (!section) throw new Error('章节不存在')
        
        if (!section.forms) {
          section.forms = []
        }
        section.forms.push(form)
        return section
      } catch (error) {
        console.error('添加表单到章节失败:', error)
        throw error
      }
    },

    // 从章节中移除表单
    async removeFormFromSection(sectionId, formId) {
      try {
        const section = this.sections.find(s => s._id === sectionId || s.id === sectionId)
        if (!section) throw new Error('章节不存在')
        
        const index = section.forms.findIndex(f => f._id === formId || f.id === formId)
        if (index !== -1) {
          section.forms.splice(index, 1)
        }
        return section
      } catch (error) {
        console.error('从章节中移除表单失败:', error)
        throw error
      }
    },

    // 更新章节中的表单顺序
    async updateFormOrder(sectionId, formIds) {
      try {
        const section = this.sections.find(s => s._id === sectionId || s.id === sectionId)
        if (!section) throw new Error('章节不存在')
        
        // 根据传入的顺序重新排列表单
        section.forms = formIds.map(id => 
          section.forms.find(f => f._id === id || f.id === id)
        ).filter(Boolean)
        
        return section
      } catch (error) {
        console.error('更新表单顺序失败:', error)
        throw error
      }
    }
  }
}) 